import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import React, { useState, useEffect } from "react";
import { PageHeader, Button, Modal, Form, Input, message } from "antd";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import {
  ArticleAddApi,
  ArticleSearchApi,
  ArticleUpdateApi,
} from "../request/api";
import moment from "moment";
import { useParams,  useLocation } from "react-router-dom";

function Edit() {
  // editor 实例
  // const [editor, setEditor] = useState<IDomEditor | null>(null)   // TS 语法
  const [editor, setEditor] = useState(null); // JS 语法
  const [form] = Form.useForm();
  // 编辑器内容
  const [html, setHtml] = useState("");
  const params = useParams();
  const location = useLocation();
  const [title, setTitle] = useState("");
  const [subTitle, setSubTitle] = useState("");


  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    // setTimeout(() => {
    //     setHtml('<p>hello world</p>')
    // }, 1500)
    if (params.id) {
      console.log(params);
      ArticleSearchApi({ id: params.id }).then((res) => {
        setTitle(res.data.title);
        setSubTitle(res.data.subTitle);
        setHtml(res.data.content);
      });
    }else{
        setTitle('')
        setSubTitle('')
        setHtml('')
    }
  }, [location.pathname]);

  // 工具栏配置
  // const toolbarConfig: Partial<IToolbarConfig> = { }  // TS 语法
  const toolbarConfig = {}; // JS 语法

  // 编辑器配置
  // const editorConfig: Partial<IEditorConfig> = {    // TS 语法
  const editorConfig = {
    // JS 语法
    placeholder: "请输入内容...",
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  //对话框
  const [isModalOpen, setIsModalOpen] = useState(false);

  // const showModal = () => {
  //   setIsModalOpen(true);
  // };

  const handleOk = (props) => {
    //
    form
      .validateFields()
      .then((values) => {
        // form.resetFields();
        console.log("Received values of form: ", values);
        let { title, subTitle } = values;
        if (params.id) {
          ArticleUpdateApi({
            id: params.id,
            title,
            subTitle,
            content: html,
          }).then((res) => {
            console.log(res);
            if (res.errCode === 0) {
              message.success(res.message);
              setTimeout(() => {
                setIsModalOpen(false);
              }, 1000);
            } else {
              message.error(res.message);
            }
          });
        } else {
          ArticleAddApi({ title, subTitle, content: html }).then((res) => {
            console.log(res);
            if (res.errCode === 0) {
              message.success("添加成功");
              setTimeout(() => {
                setIsModalOpen(false);
              }, 1000);
            } else {
              message.error(res.message);
            }
          });
        }
      })
      .catch(() => {
        return;
      });
  };

  //表单
  const onFinish = (values) => {
    console.log("Success:", values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <>
      <PageHeader
        ghost={false}
        onBack={params.id ? () => window.history.back() : null}
        title="文章编辑"
        subTitle={"当前日期：" + moment(new Date()).format("YYYY-MM-DD")}
        extra={
          <Button key="1" type="primary" onClick={() => setIsModalOpen(true)}>
            提交文章
          </Button>
        }
      ></PageHeader>
      <div
        id="div1"
        style={{ padding: "0 20px 20px", background: "#fff" }}
      ></div>
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Modal
          title="填写文章标题"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={() => {
            setIsModalOpen(false);
          }}
          okText="提交"
          cancelText="取消"
        >
          <Form
            form={form}
            name="basic"
            initialValues={{title,subTitle}}
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 24,
            }}
        
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: "请填写标题",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item label="副标题" name="subTitle">
              <Input />
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            ></Form.Item>
          </Form>
        </Modal>
        {/* onClick={()=>navigate('/edit/'+item.id)} */}
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => setHtml(editor.getHtml())}
          mode="default"
          style={{ height: "500px", overflowY: "hidden" }}
        />
      </div>
    </>
  );
}

export default Edit;
